package com.hycc.base;

public class SynLock {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{for (int i = 0; i < 10; i++) data.increment(); },"a").start();
        new Thread(()->{for (int i = 0; i < 10; i++) data.decrement(); },"b").start();
        new Thread(()->{for (int i = 0; i < 10; i++) data.increment(); },"c").start();
        new Thread(()->{for (int i = 0; i < 10; i++) data.decrement(); },"d").start();

    }
}

//判断等待，业务，通知
class Data{
    private int number = 0;

    public synchronized void increment(){
        while(number!=0){
            //等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"-->"+number);
        //通知
        this.notifyAll();
    }

    public synchronized void decrement(){
        while(number==0){
            //等待
            //等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"-->"+number);
        //通知
        this.notifyAll();
    }
}